import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:laoba_menu/views/category/Data.dart';
import 'package:laoba_menu/views/home/components/ListItem.dart';
import '../../product-detail//Detail.dart';

class Lists extends StatefulWidget {
  @override
  ListsState createState() => new ListsState();
}

class ListsState extends State<Lists> {
  Dio dio = Dio();
  List dataList = [];
  bool isFavorite = false;
  Color fontColor = Color.fromRGBO(255, 75, 54, 1);
  Color fontUnselectColor = Color.fromRGBO(200, 200, 200, 1);

  Future getData() async {
    final String url = 'http://127.0.0.1:7001/cook/findByCategoryId';
    final res = await dio.get(url, queryParameters: {'category_id': 1});
    var data = jsonDecode(res.toString());
    dataList = data['data']
        .map((i) => CategoryList.fromJson(i.cast<String, dynamic>()))
        .toList();
    setState(() {
      getWidgetList();
    });
  }

  @override
  initState() {
    super.initState();
    getData();
  }

  List<Widget> getWidgetList() {
    return dataList
        .map((item) => ListItem(
            id: item.id,
            name: item.name,
            cover: item.cover,
            create_time: item.create_time,
            desc: item.desc,
            favorite_count: item.favorite_count))
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      shrinkWrap: true,
      //水平子Widget之间间距
      crossAxisSpacing: 10.0,
      //垂直子Widget之间间距
      mainAxisSpacing: 10.0,
      //GridView内边距
      padding: EdgeInsets.all(10.0),
      //一行的Widget数量
      crossAxisCount: 2,
      childAspectRatio: 0.5,
      //子Widget列表
      children: getWidgetList(),
      physics: new NeverScrollableScrollPhysics(),
    );
  }

  void favoriteCookItem(int id) async {
    if (isFavorite) {
      final String url = 'http://127.0.0.1:7001/favorite/cancel';
      final res = await dio
          .post(url, data: {'user_id': 1, 'favorite_type': 1, 'cook_id': id});
      isFavorite = false;
    } else {
      final String url = 'http://127.0.0.1:7001/cook/setFavoriteCount';
      final res = await dio
          .post(url, data: {'user_id': 1, 'favorite_type': 1, 'id': id});
      isFavorite = true;
    }
    setState(() {});
  }
}
